package leetcode.binarysearch;

//704. 二分查找
public class Search {
    public static void main(String[] args) {
        int[] data = {-1, 0, 3, 5, 9, 12};
        System.out.println(search(data, 9));
    }

    public static int search(int[] nums, int target) {
        if (target < nums[0] || target > nums[nums.length - 1]) {
            return -1;
        }
        int p = 0;
        int q = nums.length - 1;
        int mid = p + (q - p) / 2;
        while (p <= q) {
            if (target < nums[mid]) {
                q = mid - 1;
                mid = p + (q - p) / 2;
            } else if (target > nums[mid]) {
                p = mid + 1;
                mid = p + (q - p) / 2;
            } else if (target == nums[mid]) {
                return mid;
            } else {
                return -1;
            }
        }
        return -1;
    }

    //练习二分查找
    public static int search2(int[] nums, int target) {
        int p = 0;
        int q = nums.length - 1;
        while (p <= q) {
            int mid = p + (q - p) / 2;
            if (target > nums[mid]) {
                p = mid + 1;
            } else if (target < nums[mid]) {
                q = mid - 1;
            } else if (target == nums[mid]){
                return mid;
            }else {
                return -1;
            }
        }
        return -1;
    }
}
